package com.ray.util;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.ray.woodencreate.exception.BusinessException;
import com.ray.woodencreate.exception.BusinessExceptionFactory;
import lombok.extern.slf4j.Slf4j;

import java.beans.PropertyDescriptor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.List;

/**
 * @author bo shen
 * @Description: 字符串处理
 * @Class: StringUtil
 * @Package com.tf56.bms.util
 * @date 2020/2/12 20:05
 * @company <p>Ray快速开发平台</p>
 * @updateRecord time(修改时间)  author(修改人)   desc(修改内容)
 */
@Slf4j
public class StringUtil {

    /**
     * 转字符串
     *
     * @param value
     * @return
     */
    public static String valueOf(Object value) {
        if (value != null) {
            return String.valueOf(value);
        }
        return null;
    }

    /**
     * 单个转list
     *
     * @param value
     * @return
     */
    public static List<String> asList(Object value) {
        if (value != null) {
            return Arrays.asList(String.valueOf(value));
        }
        return null;
    }

    /**
     * 把对象的空值转成null
     *
     * @param target
     */
    public static void emptyToNull(Object target) {
        try {
            if (ObjectUtil.isNotNull(target)) {
                Class<?> clazz = target.getClass();
                for (Field field : clazz.getDeclaredFields()) {
                    PropertyDescriptor pd = new PropertyDescriptor(field.getName(), clazz);
                    Method get = pd.getReadMethod();
                    Object value = get.invoke(target);
                    if (value != null) {
                        if (value instanceof String) {
                            if (StrUtil.isBlank((String) value)) {
                                Method set = pd.getWriteMethod();
                                set.invoke(target, new Object[]{null});
                            }
                        }
                    }
                }
            }
        } catch (Exception e) {
            log.info("数据转换异常", e);
            throw BusinessExceptionFactory.newException("数据转换异常");
        }
    }

    public static String nullToEmpty(String value) {
        if (StrUtil.isBlank(value)) {
            return "";
        }
        return value;
    }
}
